<?php

/**
 * business actions.
 *
 * @package    sf_sandbox
 * @subpackage business
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class businessActions extends sfActions
{

    public function executeInitData()
    {
        //$this->getConstructTreeForOldMgig();
        $this->migrateOldMgig();
        $this->flushAccountAndCommissionData();
        //$this->revalidateByParingLedger(null);
        print_r("Done");
        return sfView::HEADER_ONLY;
    }
    function flushAccountAndCommissionData()
    {
        //TRUNCATE TABLE `mlm_gold_dividend`
        //TRUNCATE TABLE `mlm_dist_pairing`
        //TRUNCATE TABLE `mlm_dist_pairing_ledger`
        //TRUNCATE TABLE `mlm_account`
        //TRUNCATE TABLE `mlm_account_ledger`
        $mlmDistributors = MlmDistributorPeer::doSelect(new Criteria());
        foreach ($mlmDistributors as $mlmDistributor) {
            $sponsorId = $mlmDistributor->getDistributorId();
            print_r("====================");
            print_r($sponsorId);
            print_r("<br>");
            print_r("packageId:".$mlmDistributor->getRankId());
            print_r("<br>");

            if ($mlmDistributor->getRankId() == null)
                continue;

            $cps = 0;
            $c = new Criteria();
            $c->add(TblDistributorPeer::F_CODE, $mlmDistributor->getDistributorCode());
            $tblDistributor = TblDistributorPeer::doSelectOne($c);
            if ($tblDistributor) {
                print_r("** old member");
                print_r("<br>");
                $c = new Criteria();
                $c->add(TblAccountPeer::F_DIST_ID, $tblDistributor->getFId());
                $c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_CPS);
                $exist = TblAccountPeer::doSelectOne($c);
                if($exist) $cps = $exist->getFBalance();
                print_r("** cps".$cps);
                print_r("<br>");
            } else {
                print_r("** base on rank".$mlmDistributor->getRankId());
                print_r("<br>");
                $packageDB = MlmPackagePeer::retrieveByPK($mlmDistributor->getRankId());
                $this->forward404Unless($packageDB);
                $cps = $packageDB->getCps();
            }

            /* ****************************************************
           * Start Calculation
           * ***************************************************/
            $ecash = 0;
            $epoint = 0;
            $dividend = 0;
            $maintenance = 0;
            $tradingPoint = $packageDB->getGoldTradingScale() * $packageDB->getPrice();
            // Once new member joined, we give 24 months x gold dividend (500 CPS = 1g, 1g = USD 80), means USD 1,920 in FOREX BALANCE, let them bet on FOREX.
            $forex = $cps / Globals::CPS_PER_GRAM_OF_GOLD * Globals::FOREX_VALUE_PER_GOLD * Globals::FOREX_MONTHS;

            if ($mlmDistributor->getDistributorId() == 1) {
                $epoint = 300000;
            }

            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_ECASH, $ecash, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_EPOINT, $epoint, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_CPS, $cps, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_GOLD, $dividend, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_MAINTENANCE, $maintenance, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_TRADING_POINT, $tradingPoint, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_FOREX, $forex, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");

            /******************************/
            /*  store Pairing points
            /******************************/
            $sponsorDistPairingDB = new MlmDistPairing();
            $sponsorDistPairingDB->setDistId($sponsorId);
            $sponsorDistPairingDB->setLeftBalance(0);
            $sponsorDistPairingDB->setRightBalance(0);
            $sponsorDistPairingDB->setFlushLimit($packageDB->getDailyMaxPairing());
            $sponsorDistPairingDB->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $sponsorDistPairingDB->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $sponsorDistPairingDB->save();

            /* ****************************************************
             * Update distributor account
             * ***************************************************/
            if ($mlmDistributor->getActiveDatetime() == null)
                continue;

            $dateArr = explode(" ", $mlmDistributor->getActiveDatetime());
            $arr = explode("-", $dateArr[0]);

            $dateUtil = new DateUtil();
            $currentDate = $dateUtil->formatDate("Y-m-d", date("Y")."-".(date("m") - 1)."-".$arr[2]) . " 00:00:00";
            $dividendDate = $dateUtil->addDate($currentDate, 30, 0, 0);

            $mlm_gold_dividend = new MlmGoldDividend();
            $mlm_gold_dividend->setDistId($sponsorId);
            $mlm_gold_dividend->setIdx(1);
            //$mlm_gold_dividend->setAccountLedgerId($this->getRequestParameter('account_ledger_id'));
            $mlm_gold_dividend->setDividendDate($dividendDate);
            $mlm_gold_dividend->setCps($cps);
            //$mlm_gold_dividend->setGoldPrice($this->getRequestParameter('gold_price'));
            //$mlm_gold_dividend->setDevidendAmount($this->getRequestParameter('devidend_amount'));
            //$mlm_gold_dividend->setRemarks($this->getRequestParameter('remarks'));
            $mlm_gold_dividend->setStatusCode(Globals::DIVIDEND_STATUS_ACTIVE);
            $mlm_gold_dividend->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_gold_dividend->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_gold_dividend->save();
        }
    }
    function getConstructTreeForOldMgig()
    {
        $c = new Criteria();
        $c->add(TblDistributorPeer::F_STATUS, "active");
        $c->addAscendingOrderByColumn(TblDistributorPeer::F_ID);
        $tblDistributors = TblDistributorPeer::doSelect($c);

        foreach ($tblDistributors as $tblDistributor) {
            $tree = "";
            $treeLevel = 1;
            $parentId = 0;
            $parentCode = "";
            $uplineId = 0;
            $uplineCode = "";
            if ($tblDistributor->getFParentId2() == 0) {
                $tree = "|".$tblDistributor->getFCode()."|";
            } else {
                $tblParentDistributor = TblDistributorPeer::retrieveByPK($tblDistributor->getFParentId());
                $tblUplineDistributor = TblDistributorPeer::retrieveByPK($tblDistributor->getFParentId2());
                $tree = $tblUplineDistributor->getTreeStructure()."|".$tblDistributor->getFCode()."|";
                $treeLevel = $tblUplineDistributor->getTreeLevel() + 1;

                $parentId = $tblParentDistributor->getFId();
                $parentCode = $tblParentDistributor->getFCode();
                $uplineId = $tblUplineDistributor->getFId();
                $uplineCode = $tblUplineDistributor->getFCode();
            }
            $tblDistributor->setTreeStructure($tree);
            $tblDistributor->setTreeLevel($treeLevel);
            $tblDistributor->setParentId($parentId);
            $tblDistributor->setParentCode($parentCode);
            $tblDistributor->setUplineDistId($uplineId);
            $tblDistributor->setUplineDistCode($uplineCode);
            $tblDistributor->save();
        }
    }
    function migrateOldMgig()
    {
        $leader = "03528277,62961296";
        $legId = "CNMGIG07,CNMGIG006";
        $leaderArr = explode(",", $leader);
        $legIdArr = explode(",", $legId);

        for ($y = 0; $y < count($leaderArr); $y++) {
            //var_dump($leaderArr[$y]);
            //var_dump($legIdArr[$y]);
            $c = new Criteria();
            $c->add(TblDistributorPeer::TREE_STRUCTURE, "%".$leaderArr[$y]."%", Criteria::LIKE);
            $c->addAscendingOrderByColumn(TblDistributorPeer::F_ID);
            $tblDistributors = TblDistributorPeer::doSelect($c);

            $uplineDistributorCode = $legIdArr[$y];
            $first = true;
            $firstUpline = true;
            foreach ($tblDistributors as $tblDistributor) {
                $tblUser = TblUserPeer::retrieveByPK($tblDistributor->getFUserId());

                $fcode = $tblDistributor->getFCode();
                $password = $tblUser->getFPassword();

                print_r("====================");
                print_r($fcode);
                print_r("<br>");

                $c = new Criteria();
                $c->add(AppUserPeer::USERNAME, $fcode);
                $app_user = AppUserPeer::doSelectOne($c);

                if (!$app_user) {
                    $app_user = new AppUser();
                }
                $app_user->setUsername($fcode);
                $app_user->setKeepPassword($tblUser->getFKeepPassword());
                $app_user->setUserpassword($tblUser->getFPassword());
                $app_user->setKeepPassword2($tblUser->getFKeepPassword2());
                $app_user->setUserpassword2($tblUser->getFPassword2());
                $app_user->setUserRole(Globals::ROLE_DISTRIBUTOR);
                $app_user->setStatusCode(Globals::STATUS_ACTIVE);
                $app_user->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->save();

                // ****************************
                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $fcode);
                $mlm_distributor = MlmDistributorPeer::doSelectOne($c);

                if (!$mlm_distributor) {
                    $mlm_distributor = new MlmDistributor();
                }
                $mlm_distributor->setDistributorCode($fcode);
                $mlm_distributor->setUserId($app_user->getUserId());
                $mlm_distributor->setStatusCode(Globals::STATUS_ACTIVE);
                $mlm_distributor->setFullName($tblDistributor->getFName());
                $mlm_distributor->setNickname($tblDistributor->getFNickname());
                $mlm_distributor->setIc($tblDistributor->getFIc());
                $mlm_distributor->setCountry($tblDistributor->getFCountry());
                $mlm_distributor->setAddress($tblDistributor->getFAddress());
                $mlm_distributor->setPostcode($tblDistributor->getFPostcode());
                $mlm_distributor->setEmail($tblDistributor->getFEmail());
                $mlm_distributor->setContact($tblDistributor->getFContact());
                $mlm_distributor->setGender($tblDistributor->getFGender());
                $mlm_distributor->setDob($tblDistributor->getFDob());
                $mlm_distributor->setBankName($tblDistributor->getFBankName());
                $mlm_distributor->setBankAccNo($tblDistributor->getFBankAccNo());
                $mlm_distributor->setBankHolderName($tblDistributor->getFBankHolderName());

                $c = new Criteria();
                if ($first == true) {
                    $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $uplineDistributorCode);
                    $first = false;
                } else {
                    $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $tblDistributor->getParentCode());
                }
                $parentDistributor = MlmDistributorPeer::doSelectOne($c);

                print_r("parent code:".$tblDistributor->getParentCode());
                print_r("<br>");

                $c = new Criteria();
                if ($firstUpline == true) {
                    $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $uplineDistributorCode);
                    $firstUpline = false;
                } else {
                    $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $tblDistributor->getUplineDistCode());
                }
                $uplineDistributor = MlmDistributorPeer::doSelectOne($c);

                $placementDatetime = date("Y/m/d h:i:s A");
                if ($tblDistributor->getFPlacementDatetime() == null) {
                    $placementDatetime = $tblDistributor->getFPlacementDatetime();
                }
                $mlm_distributor->setParentId($parentDistributor->getDistributorId());
                $mlm_distributor->setParentCode($parentDistributor->getDistributorCode());
                $mlm_distributor->setUplineDistId($uplineDistributor->getDistributorId());
                $mlm_distributor->setUplineDistCode($uplineDistributor->getDistributorCode());
                $mlm_distributor->setTreeStructure($uplineDistributor->getTreeStructure()."|".$fcode."|");
                $mlm_distributor->setTreeLevel($uplineDistributor->getTreeLevel() + 1);

                $mlm_distributor->setTotalLeft(0);
                $mlm_distributor->setTotalRight(0);
                $mlm_distributor->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

                $totalPin = 500;

                /*$c = new Criteria();
                $c->add(TblPinPeer::F_CODE, $fcode);
                $tblPin = TblPinPeer::doSelectOne($c);

                if ($tblPin) {
                    if ($tblPin->getFTotal() != null) {
                        $totalPin = $totalPin + ($tblPin->getFTotal() * 500);
                        print_r("Total Pin:" . $totalPin);
                        print_r("<br>");
                    } else {
                        print_r("No reinvest");
                        print_r("<br>");
                    }
                } else {
                    print_r("NO Pin");
                    print_r("<br>");
                }*/

                $c = new Criteria();
                $c->add(TblAccountPeer::F_DIST_ID, $tblDistributor->getFId());
                $c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_CPS);
                $exist = TblAccountPeer::doSelectOne($c);
                if($exist) $totalPin = $exist->getFBalance();

                print_r("Total Pin:" . $totalPin);
                print_r("<br>");

                if ($tblDistributor->getFLeg2() == 1) {
                    $position = Globals::PLACEMENT_LEFT;
                } else if ($tblDistributor->getFLeg2() == 2) {
                    $position = Globals::PLACEMENT_RIGHT;
                }
                print_r("Position:" . $position);
                print_r("<br>");
                $mlm_distributor->setPlacementDatetime($placementDatetime);
                $mlm_distributor->setPlacementPosition($position);

                $c = new Criteria();
                $c->add(MlmPackagePeer::CPS, $totalPin, Criteria::LESS_EQUAL);
                $c->addDescendingOrderByColumn(MlmPackagePeer::CPS);
                $packageDB = MlmPackagePeer::doSelectOne($c);

                print_r("Package:" . $packageDB->getPackageName());
                print_r("<br>");

                $mlm_distributor->setRankId($packageDB->getPackageId());
                $mlm_distributor->setRankCode($packageDB->getPackageName());
                $mlm_distributor->setInitRankId($packageDB->getPackageId());
                $mlm_distributor->setInitRankCode($packageDB->getPackageName());
                $mlm_distributor->setStatusCode(Globals::STATUS_ACTIVE);
                $mlm_distributor->setActiveDatetime($tblDistributor->getFActiveDatetime());

                $mlm_distributor->save();

                $arrs = explode("|", $uplineDistributor->getTreeStructure());
                for ($x = count($arrs); $x > 0; $x--) {
                    if ($arrs[$x] == "") {
                        continue;
                    }
                    $uplineDistDB = $this->getDistributorInformation($arrs[$x]);
                    $this->forward404Unless($uplineDistDB);
                    $totalLeft = $this->getTotalPosition($arrs[$x], Globals::PLACEMENT_LEFT);
                    $totalRight = $this->getTotalPosition($arrs[$x], Globals::PLACEMENT_RIGHT);
                    $uplineDistDB->setTotalLeft($totalLeft);
                    $uplineDistDB->setTotalRight($totalRight);
                    $uplineDistDB->save();
                }
            }
        }
    }

    function revalidateByParingLedger($distId)
    {
        $c = new Criteria();
        if ($distId != null) {
            $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, $distId);
        }
        $distributors = MlmDistributorPeer::doSelect($c);
        foreach ($distributors as $distributor) {
            print_r("DIST ID" . $distributor->getDistributorId());
            print_r("<br>");

            $this->revalidatePairing($distributor->getDistributorId(), Globals::PLACEMENT_LEFT);
            $this->revalidatePairing($distributor->getDistributorId(), Globals::PLACEMENT_RIGHT);
        }
    }

    function revalidatePairing($distributorId, $leftRight)
    {
        $balance = $this->getPairingBalance($distributorId, $leftRight);

        $c = new Criteria();
        $c->add(MlmDistPairingPeer::DIST_ID, $distributorId);
        $tbl_account = MlmDistPairingPeer::doSelectOne($c);

        if (!$tbl_account) {
            $tbl_account = new MlmDistPairing();
            $tbl_account->setDistId($distributorId);
            $tbl_account->setLeftBalance(0);
            $tbl_account->setRightBalance(0);
        }
        if (Globals::PLACEMENT_LEFT == $leftRight) {
            $tbl_account->setLeftBalance($balance);
        } else if (Globals::PLACEMENT_RIGHT == $leftRight) {
            $tbl_account->setRightBalance($balance);
        }

        $tbl_account->save();
    }

    function getPairingBalance($distributorId, $leftRight)
    {
        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId . " AND left_right = '" . $leftRight . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        $count = 0;
        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getDistributorInformation($distCode)
    {
        $c = new Criteria();

        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $distCode);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $distDB = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($distDB);

        return $distDB;
    }

    function getTotalPosition($distCode, $position)
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::PLACEMENT_POSITION, $position);
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $distCode, Criteria::NOT_EQUAL);
        $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%|" . $distCode . "|%", Criteria::LIKE);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);

        $totalDis = MlmDistributorPeer::doCount($c);
        return $totalDis;
    }

    function doSaveAccount($distId, $accountType, $credit, $debit, $transactionType, $remarks)
    {
        $c = new Criteria();
        $c->add(MlmAccountPeer::ACCOUNT_TYPE, $accountType);
        $c->add(MlmAccountPeer::DIST_ID, $distId);
        $mlm_account = MlmAccountPeer::doSelectOne($c);

        if (!$mlm_account) {
            $mlm_account = new MlmAccount();
        }
        $mlm_account->setDistId($distId);
        $mlm_account->setAccountType($accountType);
        $mlm_account->setBalance($credit - $debit);
        $mlm_account->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account->save();

        $mlm_account_ledger = new MlmAccountLedger();
        $mlm_account_ledger->setDistId($distId);
        $mlm_account_ledger->setAccountType($accountType);
        $mlm_account_ledger->setTransactionType($transactionType);
        $mlm_account_ledger->setRemark($remarks);
        $mlm_account_ledger->setCredit($credit);
        $mlm_account_ledger->setDebit($debit);
        $mlm_account_ledger->setBalance($credit - $debit);
        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->save();
    }
}
